#include <iostream>
#include <string>

#include <gloox/gloox.h>
#include <gloox/client.h>
#include <gloox/message.h>
#include <gloox/messagehandler.h>
#include <gloox/connectionlistener.h>

#include "gloox_in_c.h"

using namespace std;
using namespace gloox;

ostream& operator<<(ostream& os, Message::MessageType type) {
    switch (type) {
        case Message::Chat:
            os << "Chat";
            break;
        case Message::Error:
            os << "Error";
            break;
        case Message::Groupchat:
            os << "Groupchat";
            break;
        case Message::Headline:
            os << "Headline";
            break;
        case Message::Normal:
            os << "Normal";
            break;
        case Message::Invalid:
            os << "Invalid";
            break;
        default:
            os << "unknown type";
            break;
    }
}

ostream& operator<<(ostream& os, const Message& stanza) {
    os << "type:'" << stanza.subtype() <<  "' from:'" << stanza.from().full() << "' body:'" << stanza.body() << "'";
    return os;
}

class ConnListener : public ConnectionListener {
public:
    virtual void onConnect() {
        cout << "ConnListener::onConnect()" << endl;
    }
    virtual void onDisconnect(ConnectionError e) {
        cout << "ConnListener::onDisconnect() " << e << endl;
    }
    virtual bool onTLSConnect(const CertInfo& info) {
        cout << "ConnListener::onTLSConnect()" << endl;
        return true;
    }
};

class DemoLogHandler : public LogHandler {
 public:
    virtual void handleLog(LogLevel level, LogArea area, const std::string& message) {
        cout << level << area << message << endl;
    }
};

class Bot : public MessageHandler {
public:
    Bot() {
        // JID jid("bot@localhost");
        JID jid("yatbot0@xmpp.jp/gloox");
        client = new Client( jid, "2032103" );
        connListener = new ConnListener();
        DemoLogHandler *logh = new DemoLogHandler();
        client->registerMessageHandler( this );
        client->registerConnectionListener(connListener);
        client->logInstance().registerLogHandler(LogLevelDebug, LogAreaAll, logh);
        client->connect(true);
    }

    ~Bot() {
        delete client;
        delete connListener;
    }
 
    virtual void handleMessage( const Message& stanza, MessageSession* session = 0 ) {
        cout << "Received message: " << stanza << endl;
        Message msg(Message::Chat, stanza.from(), "Tell me more about " + stanza.body() );
        client->send( msg );
    }
 
private:
   Client* client;
   ConnListener* connListener;
};

void gloox_demo()
{
    Bot b;
}
